#include <cstdio>
#include <cuda.h>
#include <cuda_runtime.h>

__global__ void sum(float *x) {
    int g_tid = blockIdx.x * blockDim.x + threadIdx.x;
    printf("gobal thread id \t %d \n", g_tid);
    printf("block id \t %d \n", blockIdx.x);
    printf("local thread id \t %d \n", threadIdx.x);
    x[g_tid] += 1;
}

int main() {
    int N = 32;
    int nBytes = N * sizeof(float);

    float *dx = nullptr, *hx = nullptr;

    // 分配GPU内存
    cudaMalloc(&dx, nBytes);
    // 分配CPU内存
    hx = (float *)malloc(nBytes);

    printf("hx original: \n");
    for (int i = 0; i < N; i++) {
        hx[i] = i;
        printf("%g\n", hx[i]);
    }
    // CPU拷贝到GPU
    cudaMemcpy(dx, hx, nBytes, cudaMemcpyHostToDevice);

    sum<<<1, N>>>(dx);

    // GPU拷贝到CPU
    cudaMemcpy(hx, dx, nBytes, cudaMemcpyDeviceToHost);

    printf("hx current: \n");
    for (int i = 0; i < N; i++) {
        printf("%g\n", hx[i]);
    }

    // 释放资源
    cudaFree(dx);
    free(hx);
    return 0;
}
